import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/layout'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: () => import('@/views/home/index'),
        name: 'Home',
        meta: {
          title: '首页',
          cache: true
        }
      }
    ]
  },
  {
    path: '/',
    component: Layout,
    redirect: '/about',
    children: [
      {
        path: '/about',
        component: () => import('@/views/about/index'),
        name: 'User',
        meta: {
          title: '关于',
          cache: true
        }
      }
    ]
  },
  {
    path: '/',
    component: Layout,
    redirect: '/list',
    children: [
      {
        path: '/list',
        component: () => import('@/views/list/index'),
        name: 'List',
        meta: {
          title: '列表',
          cache: true
        }
      }
    ]
  },
  {
    path: '/',
    component: Layout,
    redirect: '/user',
    children: [
      {
        path: '/user',
        component: () => import('@/views/user/index'),
        name: 'User',
        meta: {
          title: '我的',
          cache: true
        }
      }
    ]
  }
]

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
const scrollBehavior = function (to, from, savedPosition) {
  // savedPosition 会在你使用浏览器前进或后退按钮时候生效
  // 这个跟你使用 router.go() 或 router.back() 效果一致
  // 这也是为什么我在 tab 栏结构中放入了一个 点击回退 的按钮

  // console.log('scrollBehavior', savedPosition, { x: 0, y: 0 })
  if (savedPosition) {
    return savedPosition
  } else {
    // 如果不是通过上述行为切换组件，就会让页面回到顶部
    return { x: 0, y: 0 }
  }
}

const router = new VueRouter({
  routes,
  scrollBehavior
})

export default router
